const utils = {
  /**
   * 字体自适应
   */
  adaptive() {
    let screenWid = document.documentElement.clientWidth;
    let fixWid = 375;
    screenWid = screenWid > 750 ? 750 : screenWid;
    let htmlFontSize = (screenWid / fixWid) * 20;
    document.documentElement.style.fontSize = parseInt(htmlFontSize) + 'px';
  },
  /**
   * 获取token并存入cookie
   */
  getToken: function () {
    let token = utils.queryString('token');
    if (!token) {
      token = utils.getCookie('token');
    }
    if (token) {
      utils.setCookie('token',token,1);
      return token;
    }
    return '';
  },
  /**
   * 读取文件
   * @param url
   * @param type
   * @param callback
   */
  loadFile(url, type, callback) {
    let elem;
    if (type == 'js') {
      elem = document.createElement("script");
      elem.src = url;
      document.body.appendChild(elem);
    } else if (type == 'css') {
      elem = document.createElement("link");
      elem.href = url;
      elem.rel = "stylesheet";
      document.head.appendChild(elem);
    } else {
      throw new Error('utils.loadFile读取文件类型错误');
    }
    if (callback) {
      elem.onload = elem.onreadystatechange = function () {
        if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
          callback();
        }
      };
    }
  },
  /**
   * cookie
   * @param name
   * @param value
   * @param time 时间[单位：天]
   */
  setCookie(name, value, time) {
    let date = new Date();
    time = time || 1;
    date.setDate(date.getDate() + time);
    document.cookie = name + "=" + value + ";path=/;domain=etcchebao.com;expires=" + date;
  },
  getCookie(name) {
    let arr = document.cookie.split("; ");
    for (let i = 0; i < arr.length; i++) {
      let arr2 = arr[i].split("=");
      if (arr2[0] === name) {
        return arr2[1];
      }
    }
    return "";
  },
  removeCookie(name) {
    utils.setCookie(name, "", -1);
  },

  //获取url查询字符串
  queryString(key) {
    return (document.location.search.match(new RegExp("(?:^\\?|&)" + key + "=(.*?)(?=&|$)")) || ['', null])[1];
  },
  /**
   * call调用-从APP进入页面，设置APP信息到cookies
   */
  setAppInfo(){
    //首页处理token
    let token = this.$route.query.token;
    let clientVersion = this.$route.query.clientVersion;
    let platform = this.$route.query.platform;
    let udid = this.$route.query.udid;
    if (token) {
      utils.setCookie("token", token);
    } else {
      utils.removeCookie("token");
    }
    clientVersion && utils.setCookie("clientVersion", clientVersion);
    platform && utils.setCookie("platform", platform);
    udid && utils.setCookie("udid", udid);
  },


  ua: navigator.userAgent,
  //ios
  isIos() {
    return utils.ua.match(/iPhone|iPod|iPad/i);
  },
  //安卓
  isAndroid() {
    return utils.ua.match(/Android/i)
  },
  //iphoneX
  isIphoneX() {
    if (utils.isIos()) {
      return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375);
    } else {
      return false;
    }
  },
  //微信
  isWeixin() {
    return utils.ua.match(/MicroMessenger/i);
  },
  //获取前缀（其实是后缀）
  getPrefix() { //截取当前host有没有后缀 如-dev 、-test等
    let wlh = window.location.host.toString();
    let prefix = '';
    if (wlh.indexOf('-dev') !== -1) {
      prefix = '-dev';
    } else if (wlh.indexOf('-test') !== -1) {
      prefix = '-test';
    }
    return prefix;
  },
  /**
   * 计算距离
   * @param distance
   * @returns {string}
   */
  computeDistance(distance) {
    distance = parseInt(distance);
    if (distance < 1000) {
      return distance + 'm';
    } else {
      return (distance / 1000).toFixed(2) + 'km';
    }
  },
  //格式化时间（毫秒）
  formatTime(ms) {
    let ss = 1000;
    let mi = ss * 60;
    let hh = mi * 60;
    let dd = hh * 24;

    let day = parseInt(ms / dd);
    let hour = parseInt((ms - day * dd) / hh);
    let minute = parseInt((ms - day * dd - hour * hh) / mi);
    let second = parseInt((ms - day * dd - hour * hh - minute * mi) / ss);
    let milliSecond = parseInt(ms - day * dd - hour * hh - minute * mi - second * ss);

    let result = {
      d: day,
      h: hour,
      mi: minute,
      s: second,
      ms: milliSecond
    };

    return result;

  },
  //格式化时间_补零（毫秒）
  formatTime_zero (ms) {
    let temp = utils.formatTime(ms);
    let result = {
      d: temp.d.toString().padStart(2, '0'),
      h: temp.h.toString().padStart(2, '0'),
      mi: temp.mi.toString().padStart(2, '0'),
      s: temp.s.toString().padStart(2, '0'),
      ms: temp.ms.toString().padStart(3, '0')
    };

    return result;

  },
};


export default utils;
